﻿using System;
using System.Windows.Media;
using System.Windows;
using System.Linq;

namespace System.Windows
{
	public static class UIElementExtensions
	{
		/// <summary>
		/// Returns the specified transform for the current element.
		/// </summary>
		/// <typeparam name="T">The System.Type of the Transform to return.</typeparam>
		/// <param name="element">The current UIElement.</param>
		/// <returns>A Transform of the specified type if found; otherwise null</returns>
		public static T Transform<T>(this UIElement element) where T : Transform
		{
			EnsureTransforms(element);

			return (element.RenderTransform as TransformGroup).Children.Where(c => c is T).Select(c => c as T).FirstOrDefault();
		}
		private static void EnsureTransforms(UIElement element)
		{
			TransformGroup group = new TransformGroup();
			if (element.RenderTransform is TransformGroup)
			{
				group = element.RenderTransform as TransformGroup;
			}

			//<TransformGroup>
			//    <ScaleTransform/>
			//    <SkewTransform/>
			//    <RotateTransform/>
			//    <TranslateTransform/>
			//</TransformGroup>

			Transform trans = group.Children.Where(c => c is ScaleTransform).FirstOrDefault();
			if (trans == null) group.Children.Add(new ScaleTransform());

			trans = group.Children.Where(c => c is SkewTransform).FirstOrDefault();
			if (trans == null) group.Children.Add(new SkewTransform());

			trans = group.Children.Where(c => c is RotateTransform).FirstOrDefault();
			if (trans == null) group.Children.Add(new RotateTransform());

			trans = group.Children.Where(c => c is TranslateTransform).FirstOrDefault();
			if (trans == null) group.Children.Add(new TranslateTransform());

			element.RenderTransform = group;
		}
	}
}
